package com.java.loginsso.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.base.utils.CookieUtils;
import com.java.loginsso.pojo.User;
import com.java.loginsso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping(value = "/rest/service/user" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@Controller
public class UserController {
    private static final String COOKIE_NAME = "CQZG_TOKEN";
    @Autowired
    private UserService userService;
    private static final ObjectMapper MAPPER = new ObjectMapper();
    /**
     *  注册
     * @return
     */
    @RequestMapping(value = "register", method = RequestMethod.GET)
    public String register() {
        return "register";
    }

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
    /*
     *  检查用户是否注册
     * 
     * @author Tigger Wu
     * @date 2018/9/19 11:04
     * @param 
     * @return 
     */
    
    @RequestMapping(value = "{param}/{type}", method = RequestMethod.GET)
    public ResponseEntity<Boolean> check(@PathVariable("param") String param,
                                         @PathVariable("type") Integer type) {
        try {
            Boolean bool = userService.check(param, type);
            if (bool == null) {
                // 参数有误
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }
            // 跟前端进行相接
            return ResponseEntity.ok(!bool);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
    /*
     *  登录校验
     * 
     * @author Tigger Wu
     * @date 2018/9/19 15:06
     * @param 
     * @return 
     */
    
    @RequestMapping(value = "doLogin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> doLogin(User user, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String token = userService.doLogin(user.getUsername(), user.getPassword());
            if (StringUtils.isEmpty(token)) {
                // 登录失败
                result.put("status", 500);
                return result;
            }

            // 登录成功，保存token到cookie
            result.put("status", 200);

            CookieUtils.setCookie(request, response, COOKIE_NAME, token);


        } catch (Exception e) {
            e.printStackTrace();
            // 登录失败
            result.put("status", 500);
        }
        return result;
    }
    /*
     *  注册用户
     * 
     * @author Tigger Wu
     * @date 2018/9/19 14:01
     * @param 
     * @return 
     */
    
    @RequestMapping(value = "doRegister", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> doRegister(@Valid User user, BindingResult bindingResult) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (bindingResult.hasErrors()) {
            // 没有通过校验
            result.put("status", "400");
            // 获取错误信息
            List<String> msgs = new ArrayList<String>();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                String msg = objectError.getDefaultMessage();
                msgs.add(msg);
            }

            result.put("data", "参数有误! " + StringUtils.join(msgs, '|'));

            return result;
        }
        try {
            Boolean bool = userService.doRegister(user);
            if (bool) {
                result.put("status", "200");
            } else {
                result.put("status", "500");
                result.put("data", "参数有误! " );
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("status", "500");
            result.put("data", "参数有误! " );
        }
        return result;
    }
    /*
     *  从缓存中拿出数据
     *
     * @author Tigger Wu
     * @date 2018/9/19 18:00
     * @param [token]
     * @return org.springframework.http.ResponseEntity<com.java.loginsso.pojo.User>
     */
    @RequestMapping(value = "{token}", method = RequestMethod.GET)
    public ResponseEntity<String> queryUserByToken(
            @RequestParam(value = "callback", required = false) String callback
            ,@PathVariable("token") String token) {
        try {
            User user = userService.queryUserByToken(token);
            String json = MAPPER.writeValueAsString(user);
            if(null ==user ){
                //没有此缓存内容
                ResponseEntity.status(HttpStatus.NOT_FOUND);
            }
            if(StringUtils.isEmpty(callback)){
                return ResponseEntity.ok(json);
            }
            return ResponseEntity.ok(callback + "(" + json + ");");
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
}
